package com.common.controller.login;

import javax.servlet.http.HttpServletRequest;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.ExcessiveAttemptsException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

@Controller
public class LoginController {
    private static Logger logger = LoggerFactory.getLogger(LoginController.class);
	@RequestMapping(value="login",method=RequestMethod.GET)
	public String getLogin(Model model){
		return "login/login";
	}
	
	@RequestMapping(value="login",method=RequestMethod.POST)
	public String getPost(HttpServletRequest req, Model model){
		
		if(SecurityUtils.getSubject().isAuthenticated()){
		return "redirect:success";
		}
		
		String exceptionClassName = (String)req.getAttribute("shiroLoginFailure"); 
		String error = null; 
		if(UnknownAccountException.class.getName().equals(exceptionClassName)) { 
		logger.info("用户名不存在");
		error = "用户名不存在";
		} else if(IncorrectCredentialsException.class.getName().equals(exceptionClassName)) 
		{ 
		logger.info("密码错误");
		error="密码错误";
		}else if(ExcessiveAttemptsException.class.getName().equals(exceptionClassName)) { 
		error = "账户被锁定"; 
		} 
		model.addAttribute("error", error); 
		return "login/login";
	}
	
	@RequestMapping(value="success",method=RequestMethod.GET)
	public String postLogin(Model model){
		return "login/success";
	}
	
	@RequestMapping(value="unauthorized",method=RequestMethod.GET)
	public String unauthorized(Model model){
		return "login/unauthorized";
	}
	
	@RequestMapping(value="syslogout",method=RequestMethod.GET)
	public String logout(){
		try {
			SecurityUtils.getSubject().logout();
		} catch (Exception e) {
			// TODO 退出
			e.printStackTrace();
		}
		return "redirect:login";
	}
}
